<template>
  <div class="container">
    <div class='main' ref="stock"></div>
  </div>
</template>

<script>
import config from '@/config'
import { mapState } from 'vuex'

const color = '#BBB'
const colorArr = [
  ['#4DF475', '#0DAA2E'],
  ['#E5DB43', '#E8B31E'],
  ['#E87F1E', '#E55643'],
  ['#5453ED', '#A66CE6'],
  ['#23DFE3', '#2D77C1']
]
export default {
  name: 'Stock',
  data() {
    return {
      chart: null,
      data: null,
      current: 1,// 当前页
      timer: null,
      pieData: null, // 当前页展示的数据
      titleSize: 0, // 标题字体大小
      ws: null
    }
  },
  created() {
    this.ws = this.$ws.getInstance()
    // 注册回调函数 等服务器回应后调用
    this.ws.registerCallback('stockData', this.getData)
  },
  mounted() {
    this.initChart()
    // this.getData()
    this.ws.send(JSON.stringify({
      action: 'getData',
      socketType: 'stockData',
      chart: 'stock',
      value: ''
    }))
    window.addEventListener('resize', this.adaptChart)
    this.chart.on('mouseover', 'series', () => {
      clearInterval(this.timer)
      this.timer = null
    })
    this.chart.on('mouseout', 'series', () => {
      this.startTimer()
    })

  },
  destroyed() {
    this.timer = null
    window.removeEventListener('resize', this.adaptChart)
    this.ws.unRegisterCallback('stockData')
    this.ws.unRegisterCallback('stockData')
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme() {
      this.chart.dispose()
      this.initChart()
      this.updateChart()
      this.$nextTick(() => {
        this.adaptChart()
      })
    }
  },
  methods: {
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = this.$echarts.init(this.$refs.stock, this.theme)
      let option = {
        title: {
          left: 20,
          top: 20,
          text: '▎' + config.title['stock'],
        },
        grid: {
          top: '25%',
          left: 'center',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          },
          formatter: '{a}<br />{b}: {c}<br />占比: {d}'
        }
      }
      // 绘制图表
      this.chart.setOption(option)
    },
    getData(data) {
      // let { data: res } = await getStock()
      // this.data = res
      this.data = data
      this.updateChart()
      this.startTimer()
    },
    updateChart() {
      // 截取数据
      this.pieData = this.data.slice((this.current - 1) * 5, this.current * 5)
      let left = 0
      let top = 0
      let ind = 0
      let sales = 0
      let series = this.pieData.map((item, index) => {
        ind = index
        if (index > 2) {
          top = 35
          index -= 2.5
        }
        left = index * 33.3
        return {
          left: left + '%',
          top: top + '%',
          name: item.name,
          type: 'pie',
          // radius: ['60%', '75%'],
          radius: ['68%', '58%'],
          avoidLabelOverlap: false,
          height: '80%',
          width: '33.33%',
          label: {
            show: true,
            position: 'center',
            formatter: arg => {
              // 因为使用center label会重叠  所以根据dataIndex 缓存销量数据 在hover库存是 依然显示销量数值
              if (arg.dataIndex == 1) {
                return arg.seriesName + '\n\n' + sales
              } else {
                sales = arg.value
              }
              return arg.seriesName + '\n\n' + arg.value
            },
            color: colorArr[ind][0]
          },
          emphasis: {
            scale: false
          },
          data: [
            {
              name: '销量',
              value: item.sales,
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                  offset: 0,
                  color: colorArr[ind][0]
                }, {
                  offset: 1,
                  color: colorArr[ind][1]
                }])
              }
            },
            {
              name: '库存',
              value: item.stock,
              itemStyle: { color }
            }
          ]
        }

      })
      let dataOption = {
        series
      }
      this.chart.setOption(dataOption)
      // 适配分辨率
      this.adaptChart()
    },
    startTimer() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.timer = setInterval(() => {
        if (this.current == 2) {
          this.current = 0
        }
        this.current++
        this.updateChart()
      }, 3000);
    },
    adaptChart() {
      this.chart.resize()
      this.titleSize = this.$refs.stock.offsetWidth / 100 * 3.6
      let adaptOption = {
        title: {
          textStyle: {
            fontSize: this.titleSize
          }
        },
        series: [
          {
            type: 'pie',
            label: {
              fontSize: this.titleSize / 1.4
            }
          },
          {
            type: 'pie',
            label: {
              fontSize: this.titleSize / 1.4
            }
          },
          {
            type: 'pie',
            label: {
              fontSize: this.titleSize / 1.4
            }
          },
          {
            type: 'pie',
            label: {
              fontSize: this.titleSize / 1.4
            }
          },
          {
            type: 'pie',
            label: {
              fontSize: this.titleSize / 1.4
            }
          }
        ]
      }
      // 绘制图表
      this.chart.setOption(adaptOption)
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
